package cn.toolck.minitomcat.util;

import cn.toolck.minitomcat.classLoader.MyClassLoader;

import javax.swing.*;
import java.io.*;
import java.net.URL;

public class StaticResourceUtil {
    public static String getAbsolutePath(String path) {
        if (path.trim().startsWith("/")) {
            path = path.substring(1);
        }
        URL resource = Thread.currentThread().getContextClassLoader().getResource("");
        String realPath = resource.getPath();
        return realPath + path;
    }

    public static InputStream getResourceAsInputStream(String path) {
        try {
            File file = new File(path);
            if (!file.isDirectory()) {
                return new FileInputStream(file);
            }
        } catch (Exception e) {
        }
        return null;
    }

    public static void writeToOutPutStreamFromInputStream(InputStream inputStream, OutputStream OutputStream) throws Exception {
        byte[] bytes = new byte[1024];
        int size = 0;
        while ((size = inputStream.read(bytes)) > 0) {
            OutputStream.write(bytes, 0, size);
        }
    }

    //读取一个文件的内容
    public static byte[] getBytes(String fileName) throws IOException{
        File file=new File(fileName);
        long len=file.length();
        byte[] raw=new byte[(int) len];

        FileInputStream fin=new FileInputStream(file);
        //一次读取class文件的全部二进制数据
        int r=fin.read(raw);
        if(r!=len){
            throw new IOException("无法读取全部文件："+r+"!="+len);
        }
        fin.close();
        return raw;
    }


    public static String getAbsolutePath(String path, MyClassLoader myClassLoader) {

        return null;
    }
}
